package com.feng.demo.hibernate.jta;

import com.feng.demo.hibernate.jta.dao.TestAmsDao;
import com.feng.demo.hibernate.jta.dao.TestDao;
import com.feng.demo.hibernate.jta.factory.DaoFactory;
import com.feng.demo.hibernate.jta.model.Test;

public class Main {
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DaoFactory daoFactory = DaoFactory.getDaoFactory();
		saveTest(daoFactory);
	}
	private static void saveTestAll(DaoFactory daoFactory) {
		TestDao testDao = daoFactory.getTestDao();
		TestAmsDao testAmsDao = daoFactory.getTestAmsDao();
		testDao.setAutoCloseSession(false);
		testDao.setAutoCommit(false);
		testAmsDao.setAutoCloseSession(false);
		testAmsDao.setAutoCommit(false);
		try{
			testAmsDao.beginTransaction();
			testDao.beginTransaction();
			Test test = new Test();
			test.setId(2);
			test.setName("Test2");
			testDao.save(test);
			/*Test test2 = new Test();
			test2.setId(1);
			test2.setName("Test1");*/
			testAmsDao.save(test);
			testDao.commitTransaction();
		}catch(Exception e){
			e.printStackTrace();
			testDao.rollbackTransaction();
		}finally{
			testDao.flushSession();
			testDao.clearSession();
			testDao.closeSession();
		}
	}
	private static void saveTest(DaoFactory daoFactory) {
		TestDao testDao = daoFactory.getTestDao();
		testDao.setAutoCloseSession(false);
		testDao.setAutoCommit(false);
		try{
			testDao.beginTransaction();
			Test test = new Test();
			test.setId(5);
			test.setName("TestEEE5");
			testDao.save(test);
			testDao.commitTransaction();
			throw new Exception("Exception!");
		}catch(Exception e){
			e.printStackTrace();
			testDao.rollbackTransaction();
		}finally{
			testDao.flushSession();
			testDao.clearSession();
			testDao.closeSession();
		}
	}
	private static void saveTestAms(DaoFactory daoFactory) {
		TestAmsDao testDao = daoFactory.getTestAmsDao();
		testDao.setAutoCloseSession(false);
		testDao.setAutoCommit(false);
		try{
			testDao.beginTransaction();
			Test test = new Test();
			test.setId(1);
			test.setName("Test1");
			testDao.save(test);
			testDao.commitTransaction();
		}catch(Exception e){
			e.printStackTrace();
			testDao.rollbackTransaction();
		}finally{
			testDao.flushSession();
			testDao.clearSession();
			testDao.closeSession();
		}
	}
}
